﻿using UnityEngine;
using ZZQFrameWork.AI;
using ZZQFrameWork;
using DG.Tweening;
using UnityEngine.EventSystems;

[RequireComponent(typeof(PlayerAnimator))]
[RequireComponent(typeof(NpcAttribute))]
[RequireComponent(typeof(NpcEquipment))]
[RequireComponent(typeof(SkillInfoComponent))]
[RequireComponent(typeof(HUDBar))]
public class PlayerAI:EntityParent
{

    #region 各个模块

    private CharacterModule characterModule
    {
        get { return ModuleManager.Instance.Get<CharacterModule>(); }
    }

    private BackpackModule backpackModule
    {
        get { return ModuleManager.Instance.Get<BackpackModule>(); }
    }

    private BattleModule battleModule
    {
        get { return ModuleManager.Instance.Get<BattleModule>(); }
    }

    #endregion

    #region Player属性

    /// <summary>
    /// 玩家动画器
    /// </summary>
    private PlayerAnimator playerAnimator;

    /// <summary>
    /// 属性管理器
    /// </summary>
    private NpcAttribute npcAttribute;

    /// <summary>
    /// 装备管理器
    /// </summary>
    private NpcEquipment npcEquipment;

    /// <summary>
    /// 技能管理器
    /// </summary>
    private SkillInfoComponent skillInfoComponent;

    /// <summary>
    /// 飘字管理器
    /// </summary>
    private HUDBar hudBar;

    private uint battleTimeId;

    public RoleDataVO Data
    {
        get { return characterModule.mainRole; }
    }

    #endregion

    #region 虚方法

    protected override void OnAwake()
    {
        playerAnimator = GetComponent<PlayerAnimator>();
        npcAttribute = GetComponent<NpcAttribute>();
        npcEquipment = GetComponent<NpcEquipment>();
        skillInfoComponent = GetComponent<SkillInfoComponent>();
        hudBar = GetComponent<HUDBar>();

        playerAnimator.PlayerAI = this;
        npcAttribute.PlayerAI = this;
        npcEquipment.PlayerAI = this;
        skillInfoComponent.PlayerAI = this;
        hudBar.PlayerAI = this;

        root = BTManager.Instance.GetRoot(1);
    }

    protected override void OnStart()
    {
        nowNode = Map.Instance.GetNodeByPos(transform.position);
    }

    protected override void OnUpdate()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (EventSystem.current.IsPointerOverGameObject()||blackBoard.AIState==AIState.FIGHT_STATE) return; //如果点击的是UI或者已经在战斗中则不执行下面
            Vector3 pointPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); //获取点击的世界坐标点
            SelectNode = Map.Instance.GetNodeByPos(pointPos);
            if (SelectNode.canWalk || SelectNode.isMonster)
            {
                findPathList = Map.Instance.aStar.FindingPath(transform.position, pointPos);
            }
            root.Proc(this);
        }
        //Debug.Log(blackBoard.AIState);
    }

    /// <summary>
    /// 是否允许AI思考
    /// </summary>
    /// <returns></returns>
    protected override int CanThink()
    {
        int error = 0;
        if (nowNode == null) error = 1;
        else if (Data.hp <= 0) error = 2;
        //Debug.Log("CanThink:"+error);
        return error;
    }

    #endregion

    #region Proc

    /// <summary>
    /// 攻击目标
    /// </summary>
    /// <returns></returns>
    public override Enum_BTState ProcAttackTo()
    {
        Debug.Log("攻击！");
        blackBoard.AIState = AIState.FIGHT_STATE;
        MonsterAI monster = blackBoard.Enemy.GetComponent<MonsterAI>();
        battleModule.StartBattle(this,monster);
        monster.BeHit(this, npcAttribute.GetAttack());
        SoundManager.Instance.PlayEffect("3");
        blackBoard.AIState = AIState.FIGHT_CD_STATE;
        //if (monster.Data.hp <= 0)
        //{
        //    //获取奖励
        //    Data.SetMonsterDrop(monster.Data.dropDataList);
        //    UIManager.Instance.CloseUI(Enum_UIType.BattlePanel);
        //}

        battleTimeId=TimerHeap.AddTimer((uint)Data.speed * 1000, 0, () =>
        {
            if (SelectNode!=null)
            {
                Debug.Log("改变为战斗状态");
                blackBoard.AIState = AIState.FIGHT_STATE;
            }
        });
        return Enum_BTState.Success;
    }

    /// <summary>
    /// 待机状态
    /// </summary>
    /// <returns></returns>
    public override Enum_BTState ProcIdle()
    {
        //Debug.Log("正在待机");
        playerAnimator.SetIdleDirection();
        return Enum_BTState.Success;
    }

    /// <summary>
    /// 移动
    /// </summary>
    /// <returns></returns>
    public override Enum_BTState ProcMoveTo()
    {
        Debug.Log("准备开始移动");
        blackBoard.AIState = AIState.MOVE_STATE;
        return Move();
    }

    #endregion

    #region AI方法

    /// <summary>
    /// 被攻击
    /// </summary>
    /// <param name="attacker">攻击者</param>
    /// <param name="atk">攻击力</param>
    public override void BeHit(EntityParent attacker, int atk)
    {
        int result = atk - Data.def;
        if(result<=0)return;
        Data.DeductHp(result);
        if (Data.hp <= 0)
        {
            battleModule.EndBattle(this);
        }
    }

    /// <summary>
    /// 移动
    /// </summary>
    /// <param name="index"></param>
    /// <returns></returns>
    private Enum_BTState Move(int index = 0)
    {
        //Debug.Log("开始移动");
        if (index >= findPathList.Count)
        {
            //后面没有格子了
            playerAnimator.SetIdleDirection();
            SelectNode = null;
            findPathList.Clear();
            blackBoard.AIState = AIState.IDLE_STATE;
            return Enum_BTState.Success;
        }
        Node node = findPathList[index];
        if (node.isMonster)
        {
            playerAnimator.SetIdleDirection();
            findPathList.Clear();
            blackBoard.AIState = AIState.IDLE_STATE;
            return Enum_BTState.Success;
        }
        playerAnimator.SetMoveDirection(GetNextNodeDir(node));
        Tweener tweener = transform.DOMove(node.pos, 0.1f);
        tweener.OnComplete(() =>
        {
            nowNode.goods = null;
            nowNode = findPathList[index];
            nowNode.goods = this.gameObject;
            index++;
            Move(index);
        });
        return Enum_BTState.Running;
    }

    /// <summary>
    /// 获取下一个移动到的node的方向
    /// </summary>
    /// <param name="node"></param>
    private Enum_PlayerMoveDirection GetNextNodeDir(Node node)
    {
        if (nowNode.x == node.x)
        {
            if (nowNode.y > node.y)
            {
                return Enum_PlayerMoveDirection.Up;
            }
            else
            {
                return Enum_PlayerMoveDirection.Down;
            }
        }
        else
        {
            if (nowNode.x > node.x)
            {
                return Enum_PlayerMoveDirection.Left;
            }
            else
            {
                return Enum_PlayerMoveDirection.Right;
            }
        }
    }

    /// <summary>
    /// 停止战斗计时
    /// </summary>
    public void StopBattleTimer()
    {
        TimerHeap.DelTimer(battleTimeId);
    }

    #endregion

}
